import React from 'react';
import {Layout, Menu , Icon ,Breadcrumb} from 'antd';
import {connect} from 'react-redux';
import {withRouter,Link} from 'react-router-dom'
import {actionCollapsed ,loadMenus,initializeMenu} from '../../redux/menu/menu.redux.js';
import {actionLogout} from '../../redux/login/login.redux';
import { getItem } from '../../utils/store';
import { injectIntl } from 'react-intl';
let leve = new Map();
let url2Leve = new Map();

@withRouter
@connect(state => state, {actionCollapsed, actionLogout,loadMenus,initializeMenu})
class SysHeader extends React.Component {
    constructor(props) {
        super(props);
        const common=this.props.intl.messages.common;
        this.extraBreadcrumbItems = null;
        this.userinfo = JSON.parse(getItem('token'));
        this.toggle = this.toggle.bind(this);
        this.handleLogout = this.handleLogout.bind(this);
        this.menuClick = this.menuClick.bind(this);
        this.goBack = this.goBack.bind(this);
        this.state={
            menusList:[]
        }
        /*三级前端菜单维护*/
        this.extraMenu=[
            {pathname:'/powerStation/chargeOrder',name:common.chargeOrder},
            {pathname:'/powerStation/equChargeOrder',name:common.chargeOrder},
            {pathname:'/powerStation/baseInfo',name:'电站信息'},
            {pathname:'/powerStation/priceInfo',name:common.ElectricityPriceInformation},
            {pathname:'/order/chargeProcess',name:common.chargingProcess},
            {pathname:'/staff/addCar',name:common.addCar},
            {pathname:'/staff/addStaff',name:common.addStaff},
            {pathname:'/finance/staffTotal',name:common.rechargeStats},
            // {pathname:'/finance/BillDetails',name:'账单详情'},
            // {pathname:'/finance/BillDetails4Month',name:'账单详情'},
            {pathname:'/finance/OrderDetails',name:'订单明细'},
            {pathname:'/company/addAccount',name:common["addSub-account"]},
            {pathname:'/monitor/monitorPlan',name:common.charPlan},
            {pathname:'/monitor/addTask',name:common.addTask},
            {pathname:'/data/carChargeReport',name:''},
            {pathname:'/interconnection/stub',name:'桩设备'},
        ]
    }


    toggle() {
        // this.props.actionCollapsed(!this.props.menu.collapsed);
        // // 设置主窗口大小
        // console.log(this.props.menu.collapsed,this.props.marginLeft)
        this.props.setSize(this.props.marginLeft);
    }

    handleLogout() {
        this.props.initializeMenu();        
        this.props.actionLogout();
        this.props.history.replace('/newLogin');
    }

    menuClick(e) {
        if (e.key === 'logout') {
            this.handleLogout();
        }
    }

    goBack(){
        if(this.props.history)
            this.props.history.goBack();
    }


    // 页面初始化完成后加载菜单
    componentWillReceiveProps(nextProps){

        let menusList = nextProps.menu.menusList;
        if(menusList && menusList.length > 0 ){
                //开始装载数据
                menusList.map(function(child) {
                    let map = new Map();
                        map.set('name',child.name);
                        map.set('url',child.url);
                        map.set('id',child.id);
                        map.set('parentId',child.parentId);
                    leve.set(child.id,map);
                });

                //开始拼URL对象
                for (let [key, value] of leve.entries()) { 
                     let leveArr =[];
                     leveArr[2] = this.strMapToObj(value);
                     let parentId = value.get('parentId');
                     if(leve.has(parentId)){
                        leveArr[1] = this.strMapToObj(leve.get(parentId));
                        let topParentId = leve.get(parentId).get('parentId');
                        if(leve.has(topParentId)){
                            leveArr[0] = this.strMapToObj(leve.get(topParentId));
                        } 
                     }
                     url2Leve.set(value.get('url'),leveArr);
                }  
            
        }
    }
    

    strMapToObj(strMap){
        let obj= Object.create(null);
        for (let[k,v] of strMap) {
            obj[k] = v;
        }
        return obj;
    }

    flag=(breadcrumbArr,index)=>{
        if(index===3){
            let menu=this.extraMenu.filter((item)=>item.pathname===this.props.location.pathname)
            breadcrumbArr[3]=menu[0]||{name:'',pathname:'/'};
        }
        if(breadcrumbArr && breadcrumbArr.length >0){
            return breadcrumbArr.map((item,index)=>{
                return(
                    item.url?
                        <Breadcrumb.Item key={index}>
                            <Link to={item.url} style={{color:'#1890ff'}}>
                                {item.name}
                            </Link>
                        </Breadcrumb.Item>
                        :
                        <Breadcrumb.Item key={index} style={{color:'#1890ff'}}>
                            {item.name}
                        </Breadcrumb.Item>)}
            )
        }
    }
    getHome = (() => {
        if(url2Leve.size>0){
            let breadcrumbArr;
            if(url2Leve.has(this.props.location.pathname)){
                breadcrumbArr= url2Leve.get(this.props.location.pathname);
                return this.flag(breadcrumbArr,2)
            }else if(this.props.location.pathname==='/'){
                breadcrumbArr=[{name:''},{name:''}];
                return this.flag(breadcrumbArr,2)
            } else{
                let lastMenu=JSON.parse(getItem('lastMenu'));
                //首页加载后直接进入页面 再去点击三级菜单没有lastMenu
                if(this.props.menu&&this.props.menu.menus){
                    var firstUrl=this.props.menu.menus[0].children[0].url
                }
                breadcrumbArr = lastMenu?url2Leve.get(lastMenu.pathname):url2Leve.get(firstUrl);
                return this.flag(breadcrumbArr,3)
            }
        }

    });

    render() {
        const common=this.props.intl.messages.common;
        return (
            <div>
            <Layout.Header style={{ background: '#fff', padding: 0,marginLeft:16,height: 50,lineHeight: '50px'}}>
                <div style={{float:'left'}}>
                    <Icon
                        className='trigger'
                        type={this.props.menu.collapsed ? 'menu-unfold' : 'menu-fold'}
                        onClick={this.toggle}
                    />
                </div>
                <div style={{float:'left'}}>
                    <Breadcrumb style={{height:'50px',lineHeight:'50px'}}>
                        {this.getHome()}
                    </Breadcrumb>
                </div>
                <Menu
                    mode="horizontal"
                    onClick={this.menuClick}
                    style={{ lineHeight: '50px', float: 'right' }}>
                    <Menu.SubMenu title={
                        <span style={{display:'flex'}}>
                            <span onClick={this.handleLogout}>{common.logout}</span>
                        </span>
                    }>
                    </Menu.SubMenu>
                </Menu>
                <span style={{ display:'flex',lineHeight: '50px', float: 'right',alignItems:'center' }}>
                    <img src={require('../../img/png/companyIcon.png')} style={{width:28,height:28,marginRight:10}}/>
                    {common.EnterpriseCode}：
                    <span style={{marginRight:10}}>{this.userinfo?this.userinfo.comPanyId:''}</span>
                    {common.account}：
                    {this.userinfo ? this.userinfo.userACcount : null}
                    &nbsp;&nbsp;&nbsp;&nbsp;|
                </span>
            </Layout.Header>
            </div>
        );
    }
}

export default injectIntl(SysHeader);